package com.plugin.uniapp.dialog;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.app.Dialog;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.plugin.uniapp.R;
import com.plugin.uniapp.utils.Logger;

import java.util.ArrayList;
import java.util.List;

public class Marquee {
    private List<String> textQueue = new ArrayList<>();
    private String currLoopText;
    private FrameLayout container;
    private TextView textView;
    private float containerWidth;
    private ObjectAnimator animator;

    public Marquee(Dialog dialog) {
        ViewGroup parent = dialog.findViewById(android.R.id.content);
        container = parent.findViewById(R.id.marquee);
        textView = parent.findViewById(R.id.marquee_text);
        container.post(() -> {
            containerWidth = container.getWidth();
            playNext();
        });
    }

    //仅播放一个且无限循环
    public void setText(String text) {
        currLoopText = text;
        playNext();
    }

    //播放多个且仅播放一次
    public void addText(String text) {
        textQueue.add(text);
        playNext();
    }

    private void playNext() {
        if (containerWidth == 0f) {
            return;
        }
        if (animator != null && animator.isRunning()) {
            return;
        }
        if (currLoopText != null) {
            textView.setText(currLoopText);
        } else {
            if (textQueue.isEmpty()) {
                return;
            }
            String currentText = textQueue.remove(0); // 取出并移除第一条
            textView.setText(currentText);
        }
        textView.setTranslationX(containerWidth);
        // 计算文字宽度（需在布局完成后获取）
        textView.post(() -> {
            int textWidth = textView.getWidth();
            animator = ObjectAnimator.ofFloat(textView, "translationX", -textWidth);
            animator.setDuration(5000);
            animator.setInterpolator(new LinearInterpolator());
            animator.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    playNext();
                }
            });
            animator.start();
        });
    }

    public void onDestroy() {
        textQueue.clear();
        if (animator != null) {
            animator.cancel();
        }
    }

    private void log(String msg) {
        Logger.log(msg, getClass(), false);
    }

    private void error(String msg) {
        Logger.error(msg, getClass(), false);
    }
}
